package org.example.view;

import org.example.calc.Operation;
import org.example.calc.OperationFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author TonySong
 * @date 2024/5/7 0007
 * @time 14:42
 */
public class MyFrame extends JFrame {

    static{
        System.out.println("静态代码块，只执行一次，且在对象创建之前完成");
    }

    private TextField txtA;
    private TextField txtB;
    private TextField txtC;

    private Button btnAdd;
    private Button btnSub;
    private Button btnMul;
    private Button btnDiv;

    private Button btnClear;

    private Button btnExit;



    {
        System.out.println("构造代码块，在创建对象之前执行，执行多次");
        this.txtA = new TextField(10);
        this.txtB = new TextField(10);
        this.txtC = new TextField(10);
        this.btnAdd = new Button("+");
        this.btnSub = new Button("-");
        this.btnMul = new Button("*");
        this.btnDiv = new Button("/");
        //设置布局：如何排列控件
        this.setLayout(new FlowLayout());

         //把控件添加到容器中
        this.add(this.txtA);
        this.add(this.txtB);
        this.add(this.txtC);
        this.add(this.btnAdd);
        this.add(this.btnSub);
        this.add(this.btnMul);
        this.add(this.btnDiv);
        //为按钮添加事件
         this.btnAdd.addActionListener(new MyAction());
         this.btnSub.addActionListener(new MyAction());
         this.btnMul.addActionListener(new MyAction());
         this.btnDiv.addActionListener(new MyAction());

    }

    private class MyAction implements  ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
           // JOptionPane.showMessageDialog(null, "你点击了" + e.getActionCommand());
            //获取值
            String a = txtA.getText();
            String b = txtB.getText();
            //判断是否为空
            if(a.equals("") || b.equals("")) {
                JOptionPane.showMessageDialog(null, "请输入数字");
            }
            //获取要执行的操作
            String op = e.getActionCommand();
            //计算
            Operation operation =OperationFactory.createOperation(op.charAt(0),Integer.parseInt(a),Integer.parseInt(b));
            //得到计算结果：并显示到文本框
            txtC.setText(String.valueOf(operation.calc()));
        }
    }

    public MyFrame() {
        this.setTitle("我的计算器");
        //设置宽和高
        this.setSize(140, 150);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置是否可视（默认是false：不可视）
        this.setVisible(true);
        //设置居中
        this.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        new MyFrame();
    }
}
